<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\OpenShopProcessEvent;
use App\Events\OpenShop\SignSiteMissionEvent;
use App\Exceptions\KfHttpResponseException;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Remote\Orm\OrmGoodsRemote;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Orm\OrmShopRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Common\CommonService;
use App\Service\Common\FsCardService;

class DesignerEquipmentService
{
    public static function detail(string $orderNo, int $sysType): array
    {
        $shopCode                = (string)OpenShopSignOrderModel::query()
            ->where('orderNo', $orderNo)
            ->value('shopCode');
        $shopInfo                = RmsShopRemote::getShopInfosByCodes([$shopCode]);
        $shopId                  = $shopInfo['shopList'][0]['id'] ?? 0;
        $shopName                = $shopInfo['shopList'][0]['name'] ?? ('编码:' . $shopCode);
        $chooseShopAddressPrefix = (string)OpenShopUserBaseInfoModel::query()
            ->where('orderNo', $orderNo)
            ->value('chooseShopAddressPrefix');
        $area                    = strlen($chooseShopAddressPrefix) ? (explode('-', $chooseShopAddressPrefix)[0]) : '-';
        $storeInfo               = OrmShopRemote::getStoreByShopId($shopId);
        $shopCreated             = $storeInfo['data']['id'] ?? 0;
        $arr = OrmGoodsRemote::equipments($sysType);
        $arr1 = OrmNewOrderRemote::myEquipments($shopId, $sysType);
        $equipmentsSpuSkuBody = OrmGoodsRemote::equipmentsSpuSku($sysType, $shopId);
        if (200 !== ($equipmentsSpuSkuBody['code'] ?? -1)) {
            throw new \Exception($equipmentsSpuSkuBody['msg'] ?? 'kfos-api系统错误');
        }
        return [
            'shopName'            => $shopName,
            'shopCode'            => $shopCode,
            'area'                => $area,
            'shopCreated'         => (bool)$shopCreated,
            'availableEquipments' => collect($arr['list'] ?? [])->map(function ($item) {
                $item['saleUnitPrice'] = round(100 * $item['saleUnitPrice']);
                return $item;
            })->toArray(),
            'availableEquipmentsSpuSku' => $equipmentsSpuSkuBody['data']['list'] ?? [],
            'orderEquipments'     => collect($arr1['data']['list'] ?? [])->map(function ($item) {
                $item['saleUnitPrice'] = round(100 * $item['saleUnitPrice']);
                $item['status'] = $item['status'] ?? OrmNewOrderRemote::NEW_ORDER_STATUS_WAIT;
                return $item;
            })->whereNotIn('status', [OrmNewOrderRemote::NEW_ORDER_STATUS_CLOSE, OrmNewOrderRemote::NEW_ORDER_STATUS_FINISH])->values()->toArray(),
        ];
    }

    public static function createNewOrder(string $orderNo, array $equipments, $operatorName, int $sysType = CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT)
    {
        $shopId = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->orderBy('id', 'desc')->value('shopId');
        return OrmNewOrderRemote::createEquipmentNewOrder($shopId, $equipments, $operatorName, $sysType);
    }

    public static function getMainProcessAndAuthUser($orderNo)
    {
        //查询主流程id
        $orderModel = OpenShopSignOrderModel::query()
                                            ->where('orderNo', $orderNo)
                                            ->first();
        $rmsInfo    = getRmsUserInfoByAuth();
        return ['rmsUser' => $rmsInfo, 'order' => $orderModel];
    }

    public static function equipmentSave(array $userInfo, string $orderNo, array $equipments)
    {
        $body = DesignerEquipmentService::createNewOrder($orderNo, $equipments,
            $userInfo['username']);
        $code = $body['code'] ?? -1;
        if (0 !== $code) {
            return [
                'msg'  => $body['msg'] ?? '订货系统开小差啦',
                'code' => $code
            ];
        }
        event(new SignSiteMissionEvent($orderNo, MissionTemplateEnum::STEP_STATUS_15,
            $userInfo['id']));
        $processAndAuthUser = DesignerEquipmentService::getMainProcessAndAuthUser($orderNo);

        // 更新space_design表step
        OpenShopSpaceDesignModel::updateStep($orderNo,
            MainProcessEnum::SPACE_DESIGN_STEP_NEXT_STEP[MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_CONFIRM_EQUIPMENT_MODULE]);

        event(new OpenShopProcessEvent($processAndAuthUser['rmsUser']->id,
            $processAndAuthUser['order']->mainProcessId, MainProcessEnum::MAIN_PROCESS_SPACE_DESIGN,
            MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_CONFIRM_EQUIPMENT_MODULE));
        (new ShopTagsService($orderNo))->updateKfosTag();

        /*
       ChangeSupport::getInstance()->buildInsertChanges(
           "设计师确认设备模块",
           [
               "goodsInfo" => collect($request->equipments)->map(function ($item) {
                   return "订货系统商品ID:{$item['id']},数量{$item['num']}";
               })->implode(';')
           ],
           ["goodsInfo" => "下单的设备信息"]
       );
       ChangeSupport::getInstance()->batchChangesWriteToOrderLog(
           OpenShopSignOrderModel::getOrderIdByOrderNo($request->orderNo),
           OpenShopSignOrderLogModel::UPDATE_SHOP_CHECK_ACCEPT,
           $userInfo['username'],
           $userInfo['id']
       );
       */

        return $body;
    }

    public static function orderDetail($id, int $sysType, int $shopId = 0)
    {
        //根据订单号获取shopId
        $temp = OrmGoodsRemote::equipments($sysType);
        $available = collect($temp['list'] ?? [])->map(function ($item) {
            $item['saleUnitPrice'] = round(100 * $item['saleUnitPrice']);
            return $item;
        })->toArray();
        if ($id) {
            //存在ID  获取对应的详情
            $data = OrmNewOrderRemote::equipmentsByNewOrder($id, $sysType);
            $info = collect($data['data']['list'] ?? [])->map(function ($item) {
                $item['saleUnitPrice'] = round(100 * $item['saleUnitPrice']);
                return $item;
            })->toArray();
        } else {
            //新建订单模板
            $info = [];
        }

        //可用的和已有的去重
        foreach ($available as $key => $value) {
            foreach ($info as $item) {
                if ($item['id'] == $value['id']) {
                    unset($available[$key]);
                }
            }
        }
        return [
            'availableEquipments'       => array_values($available),
            'availableEquipmentsSpuSku' => OrmGoodsRemote::equipmentsSpuSku($sysType, $shopId)['data']['list'] ?? [],
            'orderEquipments'           => $info
        ];
    }

    //新建&修改Orm订单

    /**
     * @param $userInfo
     * @param $orderNo
     * @param $equipments
     * @param $newOrderId
     * @return void|array
     */
    public static function saveOrmOrder($userInfo, $orderNo, $equipments, $newOrderId, int $sysType)
    {
        if ($newOrderId) {
            //修改订单
            $body = DesignerEquipmentService::updateNewOrder($orderNo, $equipments, $userInfo['username'], $newOrderId);
        } else {
            //新增订单
            $body = DesignerEquipmentService::createNewOrder($orderNo, $equipments, $userInfo['username'], $sysType);
        }
        $code = $body['code'] ?? -1;
        if (0 !== $code) {
            return $body;
        }

        if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT) {
            $stepStatus = MissionTemplateEnum::STEP_STATUS_16;
        } elseif ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE) {
            $stepStatus = MissionTemplateEnum::STEP_STATUS_17;
        } else {
            $stepStatus = 0;
        }

        if (!$newOrderId && $stepStatus) {
            //新增商家任务
            //所有软装、设备订单支付成功之后新增任务
            $siteMission = OpenShopSiteMissionModel::query()
                                                   ->where('orderNo', $orderNo)
                                                   ->where('stepStatus', $stepStatus)
                                                   ->where('status', SiteMissionEnum::STATUS_1)
                                                   ->count();

            if (!$siteMission) {
                SiteMissionService::genMission($orderNo, $stepStatus);
            }
        }

        // 新建设备相关的单子 - 发送筹备确认推送
        if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT) {
            self::equipmentSendFsToPreparation($equipments, $orderNo);
        }
    }

    // 新建设备相关的单子 - 发送筹备确认推送
    private static function equipmentSendFsToPreparation(array $equipments, string $orderNo)
    {
        dispatch(function () use ($equipments, $orderNo) {

            // 筹备
            $signOrder = OpenShopSignOrderModel::query()->where('orderNo', $orderNo)->first();

            $mainProcessId = $signOrder->mainProcessId;

            $operate = OpenShopOrderManagerModel::query()
                                                ->where('mainProcessId', $mainProcessId)
                                                ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_4)
                                                ->first();
            $operateUid = $operate->managerUid;
            $operateUsername = $operate->managerName;

            $equipmentNum = round(collect($equipments)->sum('num'), 2);

            $totalPrice          = 0;
            $availableEquipments = collect(OrmGoodsRemote::equipments()['list'] ?? [])->keyBy('id');
            $eps = collect($equipments)->map(function ($item) use (&$totalPrice, $availableEquipments) {

                $unitPrice  = $availableEquipments[$item['id']]['saleUnitPrice'] ?? 0;
                $totalPrice = round($totalPrice + $unitPrice * $item['num'], 2);

                return [
                    'id'         => $item['id'],
                    'num'        => $item['num'],
                    'name'       => $availableEquipments[$item['id']]['name'] ?? '',
                    'unitPrice'  => $unitPrice,
                    'totalPrice' => round($unitPrice * $item['num'], 2),
                ];
            })->toArray();

            $url = \App\Service\OpenShop\Feishu\BaseService::pcUrl("openShop/order/info/{$orderNo}?tab=prepareOrder");

            // 消息卡片
            $wildCardData = [
                'orderNo'      => $orderNo,
                'shopCode'     => $signOrder->shopCode,
                'merchantName' => CommonService::getUserInfoHide($signOrder->identityCardRel->name ?? '', 'name'),
                'dealName'     => $operateUsername,
                'createdAt'    => date('Y-m-d'),
                'equipmentNum' => $equipmentNum,
                'totalPrice'   => $totalPrice,
                'url'          => $url,
            ];

            $formatArr = (new FsCardService())
                ->setPath('OpenShop/feishu/notifyTemplate/equipmentNotify.json')
                ->setWildCardData($wildCardData)
                ->replace()
                ->getTemplateArr();

            $elements = [];

            foreach ($formatArr['elements'] as $k => $v) {
                $elements[] = $v;

                if ($k == 3) {

                    // 设备列表
                    foreach ($eps as $qp) {
                        $elements[] = [
                            'tag'              => 'column_set',
                            'flex_mode'        => 'none',
                            'background_style' => 'default',
                            'columns'          => [
                                [
                                    'tag'            => 'column',
                                    'width'          => 'weighted',
                                    'weight'         => 1,
                                    'vertical_align' => 'top',
                                    'elements'       => [
                                        [
                                            'tag'        => 'markdown',
                                            'content'    => (string)$qp['name'],
                                            'text_align' => 'left',
                                        ],
                                    ],
                                ],
                                [
                                    'tag'            => 'column',
                                    'width'          => 'weighted',
                                    'weight'         => 1,
                                    'vertical_align' => 'top',
                                    'elements'       => [
                                        [
                                            'tag'        => 'markdown',
                                            'content'    => (string)$qp['num'],
                                            'text_align' => 'center',
                                        ],
                                    ],
                                ],
                                [
                                    'tag'            => 'column',
                                    'width'          => 'weighted',
                                    'weight'         => 1,
                                    'vertical_align' => 'top',
                                    'elements'       => [
                                        [
                                            'tag'        => 'markdown',
                                            'content'    => (string)$qp['totalPrice'],
                                            'text_align' => 'right',
                                        ],
                                    ],
                                ],
                            ],
                        ];
                    }
                }
            }

            $formatArr['elements'] = $elements;

            (new FsCardService())->setModule(UserPermissionAuth::MODULE_OPEN_SHOP)->setKfUserIds([$operateUid])->baseSend($formatArr);

            (new ShopTagsService($orderNo))
                ->updateKfosTag(); // 生成筹备正常标签
        });
    }


    public static function updateNewOrder(string $orderNo, array $equipments, $operatorName, $newOrderId)
    {
        $shopId = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->orderBy('id', 'desc')->value('shopId');
        return OrmNewOrderRemote::updateEquipmentNewOrder($shopId, $equipments, $operatorName, $newOrderId);
    }

}
